package com.tiyende.credit.loop.ui.activity

import android.annotation.SuppressLint
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.tiyende.credit.loop.base.app.TiyendeActivityStackManager
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.databinding.TiyendeActivityLaunchBinding
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.ui.contract.IViewContract
import com.tiyende.credit.loop.ui.dialog.TiyendeLanguageDialog
import com.tiyende.credit.loop.ui.dialog.TiyendeVersionDialog
import com.tiyende.credit.loop.ui.presenter.TiyendeLaunchPresenter
import com.tiyende.credit.loop.utils.TiyendeTitleBarUtil
import com.tiyende.credit.loop.utils.helper.TiyendeAnalysisHelper
import com.tiyende.credit.loop.utils.helper.TiyendeLanguageHelper
import com.tiyende.credit.loop.utils.helper.TiyendeVersionHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import org.json.JSONObject
import java.util.TimeZone

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/5 20:18
 * @Annotation：
 */
@SuppressLint("CustomSplashScreen")
class TiyendeLaunchActivity: CommonActivity(),IViewContract.ITiyendeLaunchView {
    lateinit var binding: TiyendeActivityLaunchBinding
    var presenter: TiyendeLaunchPresenter? = null

    private var versionHelper: TiyendeVersionHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            // TODO: 更新成功，进入主界面
            presenter?.showLaunchIntentPage()
        } else {
            // 1、用户取消或失败，不处理，继续进入主界面
            // 2、如果需要强制，建议跳转应用商店，拦截进入主界面
            if (versionHelper == null) {
                presenter?.showLaunchIntentPage()
                return@registerForActivityResult
            }
            versionHelper?.handleNoUpdate {
                presenter?.showLaunchIntentPage()
            }
        }
    }

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityLaunchBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        TiyendeTitleBarUtil.setStatusBarLightMode(this, false)
        isInterceptBack(true)
        //关闭所有页面
        TiyendeActivityStackManager.finishAllActivity(TiyendeLaunchActivity::class.java)
        //启动需要重置审核中、放款中显示的公告提示次数
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_DIALOG_NOTICE_NUM,0)
    }

    override fun initTiyendeListener() {
        binding.txtAppName.setOnClickListener {
//            presenter?.getLaunchTimeZoneAction()
        }
    }

    override fun loadTiyendeData() {
        showTiyendeLoading()
        if (presenter == null){
            presenter = TiyendeLaunchPresenter(this)
        }
//        launch(Dispatchers.Main){
//            delay(1000)
//        }
        presenter?.getLaunchTimeZoneAction()
    }

    /**
     * 时区转发成功
     */
    override fun showTiyendeLaunchTimeZoneRequestData(data: String) {
        var timeZone = ""
        var zoneCode = ""
        var zoneCountry = ""

        data.split(",").apply {
            if (this.isNotEmpty()){
                timeZone = this[0].trim()
            }
            if (this.size >= 2){
                zoneCode = this[1].trim()
            }
            if (this.size >= 3){
                zoneCountry = this[2].trim()
            }
        }

        //保存时区id 改到首页保存
//        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_TIMEZONE_ID, TimeZone.getDefault().id)
        //保存转发路径
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_TIMEZONE,timeZone)
        //保存转发地区 区号
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_TIMEZONE_CODE,zoneCode)
        //保存国家标识
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_TIMEZONE_COUNTRY,zoneCountry)

        //初始化analysis lib 赋值 转发地区
        TiyendeAnalysisHelper.initAnalysisLibAtZoneSuccess()
        //添加埋点
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LAUNCH_START)

        //柬埔寨需要选择语言
        if (zoneCode == "855" || zoneCountry == "cambodia"){
            showTiyendeLanguageDialog()
            return
        }
        presenter?.getLaunchConfigsAction()
    }

    /**
     * 进入引导页
     */
    override fun showTiyendeLaunchGuidePage() {
        onIntent(TiyendeGuideActivity::class.java)
        finish()
    }

    /**
     * 进入登录页
     */
    override fun showTiyendeLaunchLoginPage() {
        onIntent(TiyendeLoginActivity::class.java)
        finish()
    }

    /**
     * 进入主页
     */
    override fun showTiyendeLaunchMainPage() {
        //保存的时区和当前时区不一致，需要进入登录页面
        if (TimeZone.getDefault().id != TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_TIMEZONE_ID)){
            showTiyendeLaunchLoginPage()
            return
        }
        onIntent(TiyendeMainActivity::class.java)
        finish()
    }

    /**
     * 版本更新Dialog
     */
    override fun showTiyendeLaunchVersionUpdateDialog() {
        val updateDialog = TiyendeVersionDialog(this,"Launch page",object : TiyendeVersionDialog.IDialogCallback{
            override fun onClick(view: View?) {
                try {
                    if (versionHelper == null){
                        versionHelper = TiyendeVersionHelper(activity = this@TiyendeLaunchActivity, isMust = true, updateLauncher)
                    }
                    versionHelper?.startVersionUpdate { presenter?.showLaunchIntentPage() }
                } catch (e: Exception) {
                    presenter?.showLaunchIntentPage()
                }
            }
        })
        updateDialog.show()
    }

    /**
     * 语言切换
     */
    private fun showTiyendeLanguageDialog(){
        val isChooseLanguage = TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_LANGUAGE_TAGS).isNotEmpty()
        if (isChooseLanguage){
            //已选择过语言
            presenter?.getLaunchConfigsAction()
            return
        }
        hiddenTiyendeLoading()
        val dataList = TiyendeLanguageHelper.queryTiyendeLanguageList()
        val languageDialog = TiyendeLanguageDialog(this,"Launch page",object : TiyendeLanguageDialog.IDialogCallback{
            override fun onLanguageSelectedItem(data: JSONObject) {
                val currentTags = TiyendeLanguageHelper.queryTiyendeCurrentLanguage()
                val tags = data.optString("tags")
                TiyendeLanguageHelper.saveTiyendeLanguage(tags)
                if (currentTags == tags){//设置和当前应用语言相同的语言，应用不会重启
                    showTiyendeLoading()
                    presenter?.getLaunchConfigsAction()
                } else {//设置和当前应用语言不同的语言，
                    //设置不同类型的语言后，应用会重启
                    TiyendeLanguageHelper.saveTiyendeLanguage(tags)
                }
            }
        })
        languageDialog.setCancelable(false)
        languageDialog.setCanceledOnTouchOutside(false)
        languageDialog.show()
        languageDialog.addTiyendeLanguageList(dataList)
    }

    override fun onResume() {
        super.onResume()
        versionHelper?.resume()
    }

    override fun requestTryAgain() {
        super.requestTryAgain()
        presenter?.getLaunchTimeZoneAction()
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LAUNCH_END)
    }
}